/**
 * 项目数据访问服务
 */
const fs = require('fs').promises;
const path = require('path');
const { PROJECTS_DIR, PROJECTS_INDEX } = require('../utils/constants');

/**
 * 读取项目索引
 */
async function readProjectsIndex() {
    try {
        const data = await fs.readFile(PROJECTS_INDEX, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        // 如果文件不存在，返回默认结构
        return {
            projects: [],
            defaultProject: null
        };
    }
}

/**
 * 保存项目索引
 */
async function saveProjectsIndex(data) {
    await fs.writeFile(PROJECTS_INDEX, JSON.stringify(data, null, 2), 'utf-8');
}

/**
 * 读取项目配置
 */
async function readProjectConfig(projectPath) {
    const configFile = path.join(PROJECTS_DIR, projectPath, 'project.json');
    const data = await fs.readFile(configFile, 'utf-8');
    return JSON.parse(data);
}

/**
 * 保存项目配置
 */
async function saveProjectConfig(projectPath, config) {
    const configFile = path.join(PROJECTS_DIR, projectPath, 'project.json');
    await fs.writeFile(configFile, JSON.stringify(config, null, 2), 'utf-8');
}

/**
 * 获取回收站项目列表
 */
async function getRecycleBinProjects() {
    const index = await readProjectsIndex();
    return index.recycleBin || [];
}

/**
 * 将项目移入回收站
 */
async function moveToRecycleBin(projectId) {
    const index = await readProjectsIndex();
    const projectIndex = index.projects.findIndex(p => p.id === projectId);
    
    if (projectIndex === -1) {
        throw new Error('项目不存在');
    }
    
    const project = index.projects[projectIndex];
    
    // 不允许删除默认项目
    if (project.id === index.defaultProject) {
        throw new Error('不能删除默认项目，请先设置其他项目为默认');
    }
    
    // 从项目列表中移除
    index.projects.splice(projectIndex, 1);
    
    // 添加到回收站
    if (!index.recycleBin) {
        index.recycleBin = [];
    }
    
    project.deletedAt = new Date().toISOString();
    index.recycleBin.push(project);
    
    // 删除该项目的上传模型缓存文件夹
    const cacheDir = path.join(PROJECTS_DIR, 'cache', 'uploadmodel', projectId);
    try {
        await fs.rm(cacheDir, { recursive: true, force: true });
        console.log(`🗑️ 已删除项目上传缓存文件夹: ${cacheDir}`);
    } catch (error) {
        // 如果缓存文件夹不存在或删除失败，只记录警告
        console.warn(`⚠️ 删除缓存文件夹失败或不存在: ${cacheDir}`, error.message);
    }
    
    await saveProjectsIndex(index);
    
    return project;
}

/**
 * 从回收站恢复项目
 */
async function restoreFromRecycleBin(projectId) {
    const index = await readProjectsIndex();
    
    if (!index.recycleBin) {
        index.recycleBin = [];
    }
    
    const recycleBinIndex = index.recycleBin.findIndex(p => p.id === projectId);
    
    if (recycleBinIndex === -1) {
        throw new Error('回收站中未找到该项目');
    }
    
    const project = index.recycleBin[recycleBinIndex];
    
    // 从回收站中移除
    index.recycleBin.splice(recycleBinIndex, 1);
    
    // 移除删除时间戳
    delete project.deletedAt;
    
    // 恢复更新时间
    project.updatedAt = new Date().toISOString();
    
    // 添加回项目列表
    index.projects.push(project);
    
    await saveProjectsIndex(index);
    
    return project;
}

/**
 * 从回收站彻底删除项目
 */
async function permanentlyDeleteProject(projectId) {
    const index = await readProjectsIndex();
    
    if (!index.recycleBin) {
        index.recycleBin = [];
    }
    
    const recycleBinIndex = index.recycleBin.findIndex(p => p.id === projectId);
    
    if (recycleBinIndex === -1) {
        throw new Error('回收站中未找到该项目');
    }
    
    const project = index.recycleBin[recycleBinIndex];
    
    // 删除项目目录
    const projectDir = path.join(PROJECTS_DIR, project.path);
    await fs.rm(projectDir, { recursive: true, force: true });
    
    // 删除该项目的上传模型缓存文件夹
    const cacheDir = path.join(PROJECTS_DIR, 'cache', 'uploadmodel', projectId);
    try {
        await fs.rm(cacheDir, { recursive: true, force: true });
        console.log(`🗑️ 已删除项目缓存文件夹: ${cacheDir}`);
    } catch (error) {
        // 如果缓存文件夹不存在或删除失败，只记录警告，不影响项目删除
        console.warn(`⚠️ 删除缓存文件夹失败或不存在: ${cacheDir}`, error.message);
    }
    
    // 从回收站中移除
    index.recycleBin.splice(recycleBinIndex, 1);
    
    await saveProjectsIndex(index);
    
    return project;
}

/**
 * 清理过期的回收站项目（30天前）
 */
async function cleanExpiredRecycleBin() {
    const index = await readProjectsIndex();
    
    if (!index.recycleBin || index.recycleBin.length === 0) {
        return { cleaned: 0, projects: [] };
    }
    
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    
    const expiredProjects = [];
    const remainingProjects = [];
    
    for (const project of index.recycleBin) {
        const deletedDate = new Date(project.deletedAt);
        
        if (deletedDate < thirtyDaysAgo) {
            expiredProjects.push(project);
            
            // 删除项目目录
            const projectDir = path.join(PROJECTS_DIR, project.path);
            try {
                await fs.rm(projectDir, { recursive: true, force: true });
                console.log(`🗑️ 已彻底删除过期项目: ${project.name} (${project.id})`);
            } catch (error) {
                console.error(`❌ 删除项目目录失败: ${project.path}`, error);
            }
            
            // 删除该项目的上传模型缓存文件夹
            const cacheDir = path.join(PROJECTS_DIR, 'cache', 'uploadmodel', project.id);
            try {
                await fs.rm(cacheDir, { recursive: true, force: true });
                console.log(`🗑️ 已删除过期项目缓存文件夹: ${cacheDir}`);
            } catch (error) {
                // 如果缓存文件夹不存在或删除失败，只记录警告
                console.warn(`⚠️ 删除缓存文件夹失败或不存在: ${cacheDir}`, error.message);
            }
        } else {
            remainingProjects.push(project);
        }
    }
    
    if (expiredProjects.length > 0) {
        index.recycleBin = remainingProjects;
        await saveProjectsIndex(index);
    }
    
    return {
        cleaned: expiredProjects.length,
        projects: expiredProjects
    };
}

/**
 * 清理所有项目缓存文件夹
 * 删除 projects/cache 目录下的所有缓存内容
 */
async function cleanAllProjectCache() {
    const cacheDir = path.join(PROJECTS_DIR, 'cache');
    
    try {
        // 检查缓存目录是否存在
        try {
            await fs.access(cacheDir);
        } catch {
            console.log('📁 缓存目录不存在，无需清理');
            return { success: true, cleaned: 0 };
        }
        
        // 读取缓存目录的所有子目录
        const entries = await fs.readdir(cacheDir, { withFileTypes: true });
        let cleanedCount = 0;
        
        // 遍历删除所有子目录和文件
        for (const entry of entries) {
            const entryPath = path.join(cacheDir, entry.name);
            try {
                if (entry.isDirectory()) {
                    await fs.rm(entryPath, { recursive: true, force: true });
                    console.log(`🗑️ 已删除缓存目录: ${entry.name}`);
                    cleanedCount++;
                } else {
                    await fs.unlink(entryPath);
                    console.log(`🗑️ 已删除缓存文件: ${entry.name}`);
                    cleanedCount++;
                }
            } catch (error) {
                console.warn(`⚠️ 删除缓存项失败: ${entry.name}`, error.message);
            }
        }
        
        if (cleanedCount > 0) {
            console.log(`✅ 缓存清理完成：已删除 ${cleanedCount} 个缓存项`);
        } else {
            console.log('✅ 缓存目录为空，无需清理');
        }
        
        return { success: true, cleaned: cleanedCount };
    } catch (error) {
        console.error('❌ 清理缓存失败:', error);
        return { success: false, error: error.message };
    }
}

module.exports = {
    readProjectsIndex,
    saveProjectsIndex,
    readProjectConfig,
    saveProjectConfig,
    getRecycleBinProjects,
    moveToRecycleBin,
    restoreFromRecycleBin,
    permanentlyDeleteProject,
    cleanExpiredRecycleBin,
    cleanAllProjectCache
};

